import { useState, useEffect } from 'react'
import { useBoolean, useEventEmitter } from 'ahooks'
import { BuildFilled, PaperClipOutlined } from '@ant-design/icons'
import { Mars3DGltf, ElementStyleName, ElementStyleData } from './Mars3Config'
import { Form, InputNumber, Input, Select, Tooltip, Drawer, Button } from 'antd'

const { TextArea } = Input
const { Option, OptGroup } = Select
// form 表单
export const FormItemModal = ({ Map, data, form, ModelUrlEvent, ColorEvent }) => {
    return (
        <>
            {data.map((item, index) => {
                switch (item.type) {
                    case 'hidden':
                        return (
                            <Form.Item
                                key={`scenesBase-FormItem-${index}`}
                                name={item.name}
                                label={item.label}
                                className="Hidden"
                                rules={
                                    item.rulesRule
                                        ? item.rulesRule
                                        : [{ required: item.rules, message: `必须填写${item.label}!` }]
                                }
                            >
                                <Input type="hidden" />
                            </Form.Item>
                        )
                    case 'input':
                        return (
                            <Form.Item
                                key={`scenesBase-FormItem-${index}`}
                                name={item.name}
                                label={item.label}
                                className="fromItem"
                                rules={
                                    item.rulesRule
                                        ? item.rulesRule
                                        : [{ required: item.rules, message: `必须填写${item.label}!` }]
                                }
                            >
                                <Input placeholder={`请输入${item.label}`} allowClear />
                            </Form.Item>
                        )
                    case 'color':
                        return (
                            <Form.Item
                                key={`scenesBase-FormItem-${index}`}
                                name={item.name}
                                label={item.label}
                                className="fromItem"
                                rules={
                                    item.rulesRule
                                        ? item.rulesRule
                                        : [{ required: item.rules, message: `必须填写${item.label}!` }]
                                }
                                onChange={e => ColorEvent.emit(e.target.value)}
                            >
                                <Input type="color" allowClear />
                            </Form.Item>
                        )
                    case 'textarea':
                        return (
                            <Form.Item
                                key={`scenesBase-FormItem-${index}`}
                                name={item.name}
                                label={item.label}
                                className="fromItem"
                                rules={
                                    item.rulesRule
                                        ? item.rulesRule
                                        : [{ required: item.rules, message: `必须填写${item.label}!` }]
                                }
                            >
                                <TextArea rows={4} placeholder={`请输入${item.label}`} allowClear />
                            </Form.Item>
                        )
                    case 'inputNumber':
                        return (
                            <Form.Item
                                key={`scenesBase-FormItem-${index}`}
                                name={item.name}
                                label={item.label}
                                className="fromItem"
                                rules={
                                    item.rulesRule
                                        ? item.rulesRule
                                        : [{ required: item.rules, message: `必须填写${item.label}!` }]
                                }
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    placeholder={`请输入${item.label}`}
                                    min={item.min}
                                    max={item.max}
                                    step={item.step}
                                />
                            </Form.Item>
                        )
                    case 'select':
                        const SelectFrom = () => {
                            useEffect(() => {
                                if (
                                    item.toString === true &&
                                    (form.getFieldValue(item.name) || form.getFieldValue(item.name) === 0)
                                )
                                    form.setFieldsValue({ [item.name]: form.getFieldValue(item.name).toString() })
                            }, [])
                            return (
                                <Form.Item
                                    name={item.name}
                                    label={item.label}
                                    className={'fromItem'}
                                    rules={
                                        item.rulesRule
                                            ? item.rulesRule
                                            : [{ required: item.rules, message: `必须选择${item.label}!` }]
                                    }
                                >
                                    <Select
                                        placeholder={`请选择${item.label}`}
                                        showSearch
                                        allowClear
                                        filterOption={(input, option) =>
                                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                        filterSort={(optionA, optionB) =>
                                            optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase())
                                        }
                                    >
                                        {Object.keys(item.select).map(key => {
                                            return (
                                                <Option key={`scenesBase-FormItem-${index}-Option-${key}`} value={key}>
                                                    {item.select[key]}
                                                </Option>
                                            )
                                        })}
                                    </Select>
                                </Form.Item>
                            )
                        }
                        return <SelectFrom key={`scenesBase-FormItem-${index}`} />
                    case 'selectGroup':
                        const SelectGroup = () => {
                            return (
                                <Form.Item
                                    name={item.name}
                                    label={item.label}
                                    className={'fromItem'}
                                    rules={
                                        item.rulesRule
                                            ? item.rulesRule
                                            : [{ required: item.rules, message: `必须选择${item.label}!` }]
                                    }
                                >
                                    <Select
                                        placeholder={`请选择${item.label}`}
                                        showSearch
                                        allowClear
                                        onChange={() => {
                                            if (form.getFieldValue('styleName'))
                                                form.setFieldsValue({ styleName: null, icon: null })
                                        }}
                                        disabled={form.getFieldValue('uuid') ? item.modifyNot : false}
                                    >
                                        {Object.keys(item.select).map((ite, index) => (
                                            <OptGroup key={`scenesBase-FormItem-SelectGroup-${index}`} label={ite}>
                                                {Object.keys(item.select[ite]).map(key => (
                                                    <Option
                                                        key={`scenesBase-FormItem-SelectGroup-${index}-${key}`}
                                                        value={key}
                                                    >
                                                        {item.select[ite][key]}
                                                    </Option>
                                                ))}
                                            </OptGroup>
                                        ))}
                                    </Select>
                                </Form.Item>
                            )
                        }
                        return <SelectGroup key={`scenesBase-FormItem-${index}`} />
                    case 'selectModel':
                        const SelectModel = () => {
                            const [StyleDrawerState, { setTrue, setFalse }] = useBoolean(false)
                            const [ImageUrl, setImageUrl] = useState('')
                            useEffect(() => {
                                Object.keys(Mars3DGltf).forEach(key => {
                                    if (Mars3DGltf[key].find(v => v.url === form.getFieldValue(item.name)))
                                        setImageUrl(
                                            Mars3DGltf[key].find(v => v.url === form.getFieldValue(item.name)).image,
                                        )
                                })
                            }, [])
                            const ModelSelectEvent = useEventEmitter()
                            ModelSelectEvent.useSubscription(val => {
                                Object.keys(Mars3DGltf).forEach(key => {
                                    if (Mars3DGltf[key].find(v => v.url === val)) {
                                        setImageUrl(Mars3DGltf[key].find(v => v.url === val).image)
                                        form.setFieldsValue({ [item.name]: val })
                                        ModelUrlEvent.emit(val)
                                        setFalse()
                                    }
                                })
                            })
                            return (
                                <>
                                    <Form.Item
                                        name={item.name}
                                        label={item.label}
                                        className={'fromItem'}
                                        rules={
                                            item.rulesRule
                                                ? item.rulesRule
                                                : [{ required: item.rules, message: `必须选择${item.label}!` }]
                                        }
                                    >
                                        <div className="centerImage">
                                            <img src={ImageUrl} alt="" />
                                            <div onClick={setTrue}>
                                                <Tooltip title="更换模型">
                                                    <PaperClipOutlined />
                                                </Tooltip>
                                            </div>
                                        </div>
                                    </Form.Item>

                                    {StyleDrawerState && (
                                        <ElementStyleSelectModel
                                            value={form.getFieldValue(item.name)}
                                            visible={StyleDrawerState}
                                            setFalse={setFalse}
                                            ModelSelectEvent={ModelSelectEvent}
                                        />
                                    )}
                                </>
                            )
                        }
                        return <SelectModel key={`scenesBase-FormItem-${index}`} />
                    case 'style':
                        const StyleForm = () => {
                            const [StyleDrawerState, { setTrue, setFalse }] = useBoolean(false)
                            const [StyleType, setStyleType] = useState('')
                            const StyleSelectEvent = useEventEmitter()
                            const [ICON, setICON] = useState('')
                            StyleSelectEvent.useSubscription(val => {
                                setFalse()
                                const { key, data } = val
                                const { image } = data
                                setICON(image)
                                form.setFieldsValue({ styleName: key })
                                if (ModelUrlEvent) ModelUrlEvent.emit(key)
                            })
                            const replaceStyle = e => {
                                setStyleType(e)
                                setTrue()
                            }
                            useEffect(() => {
                                if (item.default) {
                                    form.setFieldsValue({ [item.judge]: item.default })
                                }
                                const name = form.getFieldValue(item.name)
                                const judge = form.getFieldValue(item.judge)
                                if (judge && name) setICON(ElementStyleData[judge].type()[name].image)
                            }, [])
                            return (
                                <>
                                    <Form.Item
                                        noStyle
                                        shouldUpdate={(prevValues, currentValues) => {
                                            if (prevValues[item.judge] !== currentValues[item.judge]) setICON('')
                                            return prevValues[item.judge] !== currentValues[item.judge]
                                        }}
                                    >
                                        {({ getFieldValue }) =>
                                            getFieldValue(item.judge) ? (
                                                <Form.Item
                                                    name={item.name}
                                                    label={item.label}
                                                    className="fromItem"
                                                    rules={
                                                        item.rulesRule
                                                            ? item.rulesRule
                                                            : [
                                                                  {
                                                                      required: item.rules,
                                                                      message: `必须选择${item.label}!`,
                                                                  },
                                                              ]
                                                    }
                                                >
                                                    {ICON ? (
                                                        <div className="centerImage">
                                                            <div
                                                                onClick={() => replaceStyle(getFieldValue(item.judge))}
                                                            >
                                                                <Tooltip title="更换样式">
                                                                    <BuildFilled />
                                                                </Tooltip>
                                                            </div>
                                                            <img alt="" src={ICON} />
                                                        </div>
                                                    ) : (
                                                        <div
                                                            className="saveCenter"
                                                            onClick={() => replaceStyle(getFieldValue(item.judge))}
                                                        >
                                                            选择 {ElementStyleName[getFieldValue(item.judge)]} 样式
                                                        </div>
                                                    )}
                                                </Form.Item>
                                            ) : null
                                        }
                                    </Form.Item>
                                    {StyleDrawerState && (
                                        <ElementStyleSelectModal
                                            visible={StyleDrawerState}
                                            setFalse={setFalse}
                                            type={StyleType}
                                            StyleSelectEvent={StyleSelectEvent}
                                        />
                                    )}
                                </>
                            )
                        }
                        return <StyleForm key={`scenesBase-FormItem-${index}`} />
                    case 'center':
                        const CenterForm = () => {
                            const [centerData, setCenterData] = useState({})
                            const SaveCenterFc = () => {
                                const center = Map.getCameraView()
                                const { _lng, _lat, _alt } = Map.getCenter()
                                setCenterData(center)
                                form.setFieldsValue({
                                    center,
                                    longitude: _lng,
                                    latitude: _lat,
                                    altitude: _alt,
                                    rotate: center.heading,
                                })
                            }
                            useEffect(() => {
                                if (form.getFieldValue(item.name) && JSON.stringify(form.getFieldValue()) !== '{}') {
                                    let center = form.getFieldValue(item.name)
                                    if (typeof center === 'string') center = JSON.parse(center)
                                    setCenterData(center)
                                }
                            }, [])
                            return (
                                <Form.Item
                                    name={item.name}
                                    label={item.label}
                                    className="fromItem"
                                    rules={
                                        item.rulesRule
                                            ? item.rulesRule
                                            : [{ required: item.rules, message: `必须选择${item.label}!` }]
                                    }
                                >
                                    {centerData && JSON.stringify(centerData) !== '{}' ? (
                                        <div className="BtnList">
                                            <Button onClick={() => Map.centerAt(centerData)}>视角回归</Button>
                                            <Button onClick={SaveCenterFc}>重新定位</Button>
                                        </div>
                                    ) : (
                                        <div className="BtnList">
                                            <Button onClick={SaveCenterFc}>定位视角</Button>
                                        </div>
                                    )}
                                </Form.Item>
                            )
                        }
                        return <CenterForm key={`scenesBase-FormItem-${index}`} />
                    default:
                        return (
                            <div key={`scenesBase-FormItem-${index}`} className="fromItem">
                                格式不支持
                            </div>
                        )
                }
            })}
        </>
    )
}

// 元素样式选择窗
const ElementStyleSelectModal = ({ visible, setFalse, type, StyleSelectEvent }) => {
    return (
        <Drawer
            className="ElementsDrawer"
            title={`${ElementStyleData[type].name} 样式选择`}
            placement="right"
            closable={false}
            onClose={setFalse}
            open={visible}
        >
            <div className="ElementsBox">
                {Object.keys(ElementStyleData[type].type()).map((item, index) => (
                    <img
                        key={`ElementStyleDataImages${index}`}
                        src={ElementStyleData[type].type()[item].image}
                        alt={ElementStyleData[type].type()[item].image}
                        onClick={() => StyleSelectEvent.emit({ key: item, data: ElementStyleData[type].type()[item] })}
                    />
                ))}
            </div>
        </Drawer>
    )
}
// 小模型选择
const ElementStyleSelectModel = ({ value, visible, setFalse, ModelSelectEvent }) => {
    const [SelectNumber, setSelectNumber] = useState('车辆')
    const [SelectUrl, setSelectUrl] = useState(value)

    return (
        <Drawer
            className="ElementsDrawer"
            title={`选择小模型`}
            placement="right"
            closable={false}
            onClose={setFalse}
            open={visible}
        >
            <Select className="ModelSelect" defaultValue={SelectNumber} onChange={e => setSelectNumber(e)}>
                {Object.keys(Mars3DGltf).map((key, index) => (
                    <Option key={`ModelList${index}`} value={key}>
                        {key}
                    </Option>
                ))}
            </Select>
            <div className="ModelListBox">
                {Mars3DGltf[SelectNumber].map((item, index) => (
                    <div
                        key={`ModelListBox${index}`}
                        style={{ border: `1px solid ${SelectUrl === item.url ? '#446EFE' : 'white'}` }}
                        onClick={() => {
                            setSelectUrl(item.url)
                            ModelSelectEvent.emit(item.url)
                        }}
                    >
                        <img src={item.image} alt="" />
                        <div>{item.name}</div>
                    </div>
                ))}
            </div>
        </Drawer>
    )
}

export const ClickFromModal = ({ form, ModelList, VideoList }) => {
    const TargetSelect = e => {
        if (form) form.resetFields(e)
    }
    return (
        <>
            <Form.Item className="fromItem" name="uuid" label="uuid" hidden>
                <Input />
            </Form.Item>
            <Form.Item
                className="fromItem"
                name="tableName"
                label="事件名称"
                rules={[{ required: true, message: '必须填写点击事件的名称!' }]}
            >
                <Input placeholder="请输入点击事件的名称" />
            </Form.Item>
            <Form.Item
                className="fromItem"
                name="sortId"
                label="排序"
                rules={[{ required: true, message: '必须填写排序!' }]}
            >
                <InputNumber style={{ width: '100%' }} placeholder="请输入排序" />
            </Form.Item>
            <Form.Item
                className="fromItem"
                name="isEnabled"
                label="是否启用"
                rules={[{ required: true, message: '必须选择事件状态!' }]}
            >
                <Select placeholder="请选择事件状态!">
                    <Option value={0}>关闭</Option>
                    <Option value={1}>启用</Option>
                </Select>
            </Form.Item>
            <Form.Item
                className="fromItem"
                name="styleName"
                label="事件样式"
                rules={[{ required: true, message: '必须选择事件样式!' }]}
            >
                <Select placeholder="请选择事件样式!" onChange={() => TargetSelect(['target'])}>
                    <Option value={0}>自定义事件</Option>
                    <Option value={1}>智能机器人</Option>
                </Select>
            </Form.Item>

            <Form.Item
                className="fromItem"
                name="target"
                label="事件类型"
                rules={[{ required: true, message: '必须选择事件类型!' }]}
            >
                <Select placeholder="请选择事件类型!" onChange={() => TargetSelect(['url'])}>
                    <Option value={0}>模型</Option>
                    <Option value={1}>进度</Option>
                    <Option value={2}>监控</Option>
                    <Option value={3}>数据</Option>
                    <Option value={4}>全景</Option>
                </Select>
            </Form.Item>

            <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.gender === currentValues.gender}>
                {({ getFieldValue, resetFields }) => {
                    switch (getFieldValue('target')) {
                        case 0:
                            return (
                                <Form.Item
                                    className="fromItem"
                                    name="url"
                                    label="模型"
                                    rules={[{ required: true, message: '必须选择展示的模型!' }]}
                                >
                                    <Select
                                        placeholder="请选择模型"
                                        showSearch
                                        filterOption={(input, option) =>
                                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {ModelList &&
                                            ModelList.map(item => (
                                                <Select.Option key={item.uuid} value={item.uuid}>
                                                    {item.tableName}
                                                </Select.Option>
                                            ))}
                                    </Select>
                                </Form.Item>
                            )
                        case 1:
                            return (
                                <Form.Item
                                    className="fromItem"
                                    name="url"
                                    label="对比模型"
                                    rules={[{ required: true, message: '必须选择展示的模型!' }]}
                                >
                                    <Select
                                        placeholder="请选择模型"
                                        showSearch
                                        filterOption={(input, option) =>
                                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {ModelList &&
                                            ModelList.map(item => (
                                                <Select.Option key={item.uuid} value={item.uuid}>
                                                    {item.tableName}
                                                </Select.Option>
                                            ))}
                                    </Select>
                                </Form.Item>
                            )
                        case 2:
                            return (
                                <Form.Item
                                    className="fromItem"
                                    name="url"
                                    label="监控摄像头"
                                    rules={[{ required: true, message: '必须选择摄像头!' }]}
                                >
                                    <Select
                                        placeholder="请选择摄像头"
                                        mode="multiple"
                                        showSearch
                                        filterOption={(input, option) =>
                                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {VideoList &&
                                            VideoList.map(item => (
                                                <Select.Option key={item.uuid} value={item.uuid}>
                                                    {item.tableName}
                                                </Select.Option>
                                            ))}
                                    </Select>
                                </Form.Item>
                            )
                        case 3:
                            return (
                                <Form.Item className="fromItem" name="url" label="数据" rules={[{ required: true }]}>
                                    <Input placeholder="临时数据" />
                                </Form.Item>
                            )
                        case 4:
                            return (
                                <Form.Item
                                    className="fromItem"
                                    name="url"
                                    label="全景"
                                    rules={[
                                        { required: true },
                                        { type: 'url', warningOnly: true },
                                        { type: 'string', min: 6 },
                                    ]}
                                >
                                    <Input placeholder="请输入720全景的路径" />
                                </Form.Item>
                            )
                        default:
                            return null
                    }
                }}
            </Form.Item>
        </>
    )
}
